<template>
  <div id="person-list" class="app-container">
    <list-search-bar
      ref="searchbar"
      :search-rule="searchRule"
      :showClear="searchRule.length"
      @submit="getList($event, pageInfo)"
      @add="showEdit()"
      @update:value="searchData = $event"
    />
    <list-table
      :showEdit="permissions.edit"
      @edit="showEdit($event)"
      @remove="remove"
      :showRemove="false"
      v-loading="listLoading"
      :listRule="editRule"
      :listData="listData"
      btnGroupWidth="280px"
      :tableHeight="tableHeight - 30"
    >
      <template slot="btn-group" slot-scope="{ row }">
        <el-button
          slot="reference"
          size="mini"
          type="primary"
          @click="lock(row)"
          >分配菜单
        </el-button>
      </template>
    </list-table>
    <pagination
      :page-sizes="[20]"
      :page-size="pageInfo.pageSize"
      :current-page="pageInfo.pageNo"
      :total="pageInfo.total"
      @pagination="getList(searchData, { ...pageInfo, pageNo: $event.page })"
    />
    <back-to-top
      :visibility-height="300"
      :back-position="0"
      transition-name="fade"
    />
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      v-dialogDrag
      :visible.sync="editDialog"
      v-loading="editLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="编辑账号"
    >
      <form-create
        v-model="editFormInstance"
        :value.sync="editData"
        :rule="editRule"
        :option="editOptions"
      />
      <template slot="footer">
        <el-button size="mini" type="primary" @click="update(editData)"
          >提交</el-button
        >
        <el-button size="mini" @click="reset">重置</el-button>
      </template>
    </el-dialog>

    <!-- Topo -->
    <el-dialog
      :close-on-click-modal="false"
      width="600px"
      v-dialogDrag
      :visible.sync="topoDialog"
      v-loading="topoLoading"
      custom-class="widget-dialog widget-form center no-margin color-white black-bg2"
      title="分配菜单"
    >
      <div class="widget-tree">
        <el-tree
          v-if="topoDialog"
          ref="treeNode"
          show-checkbox
          :data="menuTree"
          :props="defaultProps"
          :render-after-expand="true"
          :expand-on-click-node="false"
          class="black-bg color-white"
          style="padding: 10px"
          @check-change="topoChange"
          :default-checked-keys="topoShowList"
          :check-on-click-node="true"
          node-key="id"
        >
        </el-tree>
      </div>
      <template slot="footer">
        <el-button size="mini" type="primary" @click="setMenu(editData)"
          >提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  sysGetRoleList as searchApi, //获取列表的api
  sysAddRole as addApi, //新增数据的api
  sysEditRole as updateApi, //更新、新增数据的api
  sysDeleteRole as removeApi, //删除数据的api
  sysGetRoleByUserId as detailApi, //详情api
  sysGetMenuList, //菜单列表
  sysInsertRoleMenu, //分配菜单
  sysGetMenuListByRoleId //获取当前角色菜单
} from "@/api";
import { editRule, searchRule } from "@/formRules/RoleListRules";
import { editFormOptions, getData } from "@/formRules";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations.js";
import { translateDataToTree } from "@/utils/parentSon";
import { topoList } from "@/constants/topo";
import { mapState } from "vuex";
import mixin from "@/mixins/tableAutoHeight";
export default {
  name: "PersonList",
  configurations: {
    title: "角色管理",
    isDefault: true,
    show: true
  },
  mixins: [mixin],
  data() {
    return {
      editRule: editRule(),
      listData: [],
      searchRule: searchRule(),
      searchData: {}, //搜索表单数据
      editFormInstance: {},
      editData: {},
      editOptions: editFormOptions(),
      editDialog: false,
      editLoading: false,
      listLoading: false,
      toReview: 0,
      pageInfo: {
        page: 1,
        size: 20,
        total: 0
      },
      permissionList: [], //权限列表
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      topoList: translateDataToTree(topoList()),
      topoDialog: false,
      topoLoading: false,
      topoShowList: [],
      roleDialog: false,
      roleLoading: false,
      menuList: []
    };
  },
  // 在路由导航进来之前检查权限
  beforeRouteEnter(from, to, next) {
    const permissionList = checkPermission(to.path);
    if (permissionList.length) {
      next(vm => {
        vm.permissionList = permissionList;
      });
      return;
    }
    next({
      name: "403"
    });
  },
  mounted() {
    console.log("this.$route");
    console.log(this.$route);
    this.topoList = this.topoList.filter((e, index) => index == 0);
    console.log(this.topoList);
    this.getList(this.searchData, this.pageInfo); 
    this.getMenu(); 
  },
  computed: {
    // 根据获取的权限列表此处返回各个权限的显示与否
    permissions() {
      return ["edit", "remove", "add"].reduce((pre, cur) => {
        pre[cur] = true;
        // isDev ? true : this.permissionList.includes(cur);
        return pre;
      }, {});
    },
    menuTree() {
      return translateDataToTree(this.menuList);
    },
    ...mapState(["user"]),
    userName() {
      return this.user.username;
    }
  },
  methods: {
    getMenu() {
      sysGetMenuList({ page: 1, size: 1000 }).then(({ code, data }) => {
        this.menuList = data.list;
        this.menuList.forEach(element => {
          if (element.parent) {
            element.parentId = Number(element.parent);
          } else {
            element.parentId = element.parent;
          }
        });
      });
    },
    checkReview() {
      searchApi({
        isLock: 1,
        hasOpenid: 1,
        name: "",
        position: "",
        pageSize: 1000,
        pageNo: 1
      }).then(({ data }) => {
        this.toReview = data.dataList.length;
      });
    },
    searchReview() {
      this.searchData.isLock = 1;
      this.searchData.hasOpenid = 1;
      this.searchData.name = "";
      this.searchData.position = "";
      this.getList(this.searchData, this.pageInfo);
    },

    /**
     * @name 查询列表
     * @param {Object} query 查询参数，一般为this.searchData
     * @param {Object} pageInfo 页面参数，包括pageSize和pageNo
     * @description 调用成功则刷新listData
     */
    getList(query, pageInfo) {
      this.listLoading = true;
      const queryParam = {
        ...pageInfo,
        userName: this.userName,
        ...query
      };
      searchApi(queryParam)
        .then(({ code, data }) => {
          console.log(data);
          if (code == 200) {
            this.listData = data.list;
            this.pageInfo.total = data.total;
          }
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 编辑表单
     * @param {Object} row 表单数据，新增时为空
     * @description 调用成功打开表单对话框
     */
    showEdit(row) {
      console.log("row", row);
      if (!row) {
        this.editData = getData(editRule());
        this.editDialog = true;
      } else {
        // detailApi({ id: row.id }).then((res) => {
        //   const { data } = res;
        this.editData = row;
        this.editDialog = true;
        // });
      }
    },
    /**
     * @name 更新数据
     * @param editData 编辑的数据体
     * @description 调用成功关闭对话框并且刷新表单
     */
    update(editData) {
      if (!this.validation()) return;
      this.editLoading = true;
      if (editData.id) {
        updateApi(editData)
          .then(() => {
            this.$notified.success({
              message: "更新数据成功"
            });
            // this.$refs?.searchbar.reset();
            this.getList(this.searchData, this.pageInfo);
            this.editDialog = false;
            this.topoDialog = false;
          })
          .finally(() => (this.editLoading = false));
      } else {
        addApi(editData)
          .then(() => {
            this.$notified.success({
              message: "更新数据成功"
            });
            // this.$refs?.searchbar.reset();
            this.getList(this.searchData, this.pageInfo);
            this.editDialog = false;
          })
          .finally(() => (this.editLoading = false));
      }
    },
    /**
     * @name 表单验证
     * @description 如果有则在此处写入逻辑
     * @returns {Boolean} 表单验证结果
     */
    validation() {
      return true;
    },
    /**
     * @name 删除数据项
     * @description 成功后会刷新列表
     */
    remove(row) {
      this.listLoading = true;
      removeApi({
        roleId: row.id
      })
        .then(() => {
          this.$notified.success({
            message: "删除成功"
          });
          this.getList(this.searchData, this.pageInfo);
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    /**
     * @name 重置表单数据
     */
    reset() {
      this?.editFormInstance?.resetFields();
    },
    handleTreeNodeClick(e) {},
    lock(item) {
      this.editData = item;
      this.topoShowList = [];
      sysGetMenuListByRoleId({ roleId: item.id }).then(({ data }) => {
        if (data.length) {
          data.forEach(e => {
            this.topoShowList.push(e.id);
          });
        } else {
          this.topoShowList = [];
        }
        this.$nextTick(() => {
          this.topoDialog = true;
        });
      });
    },
    setMenu() {
      let param = {
        list: [],
        roleId: this.editData.id
      };
      if (this.topoShowList.length) {
        this.topoShowList.forEach(e => {
          param.list.push(e);
        });
      }
      sysInsertRoleMenu(param)
        .then(res => {
          if (res.code == 200) {
            this.$notified.success({
              message: "更新数据成功"
            });
            this.getList(this.searchData, this.pageInfo);
          } else {
            this.$notified.error(res.msg);
          }

          this.editDialog = false;
          this.topoDialog = false;
        })
        .finally(() => (this.editLoading = false));
    },
    topoChange() {
      let list = this.$refs.treeNode.getCheckedKeys();
      this.topoShowList = list;
      this.editData.topoId = list.toString();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
#idName {
  position: relative;
  overflow: hidden;
}
</style>
